package com.congee02.sw.var;

public class MaxConsecutiveAnswers {

    public int maxConsecutiveAnswers(String answerKey, int k) {
        char[] cs = answerKey.toCharArray();
        return Math.max(maxConsecutiveAnswers(cs, 'T', k), maxConsecutiveAnswers(cs, 'F', k));
    }

    private int maxConsecutiveAnswers(char[] cs, char target, int k) {

        int n = cs.length;

        boolean f = cs[0] == target;
        // l = r = 0
        int targetCnt = cs[0] == target ? 1 : 0;
        int ans = f ? 0 : 1;

        int l = 0;
        for (int r = 1 ; r < n ; r ++ ) {
            // 合法化窗口之一:
            // 1. 先处理新加入的元素
            // 2. 判断是否合法，若不合法则右移左边界
            if (cs[r] == target) {
                targetCnt ++;
            }
            while (targetCnt > k) {
                if (cs[l ++] == target) {
                    targetCnt --;
                }
            }
            ans = Math.max(ans, r - l + 1);
        }
        return ans;
    }

}
